package com.apposcopy.ella.runtime;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class HttpResponseRecorder extends Recorder {

	private static final int EOF = -1;
	private static final String TAG = HttpResponseRecorder.class.getSimpleName();
	/**
     * The default buffer size ({@value}) to use for 
     * {@link #copyLarge(InputStream, OutputStream)}
     * and
     * {@link #copyLarge(Reader, Writer)}
     */
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    
    @Override
	public void getContext(Context context) {
		if(Ella.applicationContext == null){
			Ella.applicationContext = context.getApplicationContext();
		}
	}

	public synchronized InputStream convertToArrayStream(URLConnection urlConnection) throws IOException{
    	try{
    		ByteArrayOutputStream bos = new ByteArrayOutputStream();
    		copy(urlConnection.getInputStream(), bos);
    		byte[] bytes = bos.toByteArray();
    		return new ByteArrayInputStream(bytes);
    	}catch(IOException e){
    		return urlConnection.getInputStream();
    	}
    }
    
	@Override
	public synchronized InputStream sendHttpMessage(URLConnection urlConnection) throws IOException{
		Intent sendIntent = new Intent();
		sendIntent.setAction("edu.iscas.appcheckclient.broadcastreceiver.SEND_HTTP_MESSAGE");
		URL url = urlConnection.getURL();
		sendIntent.putExtra("PROTOCOL", url.getProtocol());
		sendIntent.putExtra("HOST", url.getHost());
		sendIntent.putExtra("PORT", url.getPort());
		sendIntent.putExtra("FIlE", url.getFile());
		sendIntent.putExtra("REF", url.getRef());
		sendIntent.putExtra("USERINFO", url.getUserInfo());
		try{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			copy(urlConnection.getInputStream(), bos);
			byte[] bytes = bos.toByteArray();
			sendIntent.putExtra("RESPONSE", bytes);
			
			String res = new String(bytes);
			Log.d(TAG, res);
			
			if(Ella.applicationContext != null){
				Log.d(TAG, "sendHttpMessage");
				Ella.applicationContext.sendBroadcast(sendIntent);
			}else{
				Log.e(TAG , "No Context found");
			}
			
//			BufferedReader in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
//            String line;StringBuilder sb = new StringBuilder();
//            while ((line = in.readLine()) != null) {
//                sb.append(line);
//                Log.d(TAG, "line " + line);
//            }
//            Log.d(TAG, sb.toString());
			return new ByteArrayInputStream(bytes);
		}catch(IOException e){
			//return the initial stream
			return urlConnection.getInputStream();
		}
	}
	
    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }
    
    public static long copyLarge(InputStream input, OutputStream output)
            throws IOException {
        return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
    }
    
    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
            throws IOException {
        long count = 0;
        int n = 0;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

}
